# MT::I18N for Encode.pm
#
# Release 0.04 (Mar 26, 2005)
#
# This software is provided as-is. You may use it for commercial or 
# personal use. If you distribute it, please keep this notice intact.
#
# Copyright (c) 2004,2005 Hirotaka Ogawa

package MT::I18N;

use strict;
use MT::ConfigMgr;
use MT::Util qw(remove_html);
use Encode qw/encode decode resolve_alias/;
use Encode::Guess qw/euc-jp shiftjis 7bit-jis/;

no warnings 'redefine';
sub guess_encoding {
    my ($text) = @_;
    my $enc = Encode::Guess::guess_encoding($text);
    return $enc->name if ref $enc;
    if ($enc) {
	my %code = map { ($_, 1) } split / or /, $enc;
	my ($euc,$sjis,$utf8) = (0,0,0);

	$utf8 = length(decode('utf8', $text)) if $code{'utf8'};
	return 'utf8' if $utf8;

	$sjis = length(decode('shiftjis', $text)) if $code{'shiftjis'};
	$euc = length(decode('euc-jp', $text)) if $code{'euc-jp'};
	return 'shiftjis' if $sjis > $euc;
	return 'euc-jp' if $euc;
    }
    $enc = MT::ConfigMgr->instance->PublishCharset || 'utf8';
    return $enc;
}
use warnings 'redefine';

sub encode_text {
    my ($text, $from, $to) = @_;
    if (!$from) {
        $from = guess_encoding($text);
    }
    if (!$to) {
	$to = MT::ConfigMgr->instance->PublishCharset || 'utf8';
    }
    if (resolve_alias($from) eq resolve_alias($to)) {
      return $text;
    }
    return encode($to, decode($from, $text));
}

sub substr_text {
    my ($text, $startpos, $length) = @_;
    my $enc = guess_encoding($text);
    my $decoded = decode($enc, $text);
    $decoded = $length ? substr($decoded, $startpos, $length) : substr($decoded, $startpos);
    return encode($enc, $decoded);
}

sub wrap_text {
    my ($text, $cols, $tab_init, $tab_sub) = @_;
    my $enc = guess_encoding($text);
    $cols ||= 72;
    my $decoded = decode($enc, $text);

    my (@lines, $len, $i, $letter, $llen);
    while ($decoded =~ m/(.)/sg) {
	$letter = $1;
	$llen = ($letter =~ m/\p{ASCII}/) ? 1 : 2;
	if ($len + $llen > $cols) {
	    $i++;
	    $len = 0;
	}
	$lines[$i] .= $letter;
	$len += $llen;
    }
    $lines[$i] or pop @lines;
    $decoded = join "\n", @lines;
    return encode($enc, $decoded);
}

sub length_text {
    my ($text) = @_;
    my $enc = guess_encoding($text);
    return length(decode($enc, $text));
}

sub first_n_text {
    my ($text, $length) = @_;
    $text = remove_html($text);
    $text =~ s/(\r?\n)+/ /g;
    return substr_text($text, 0, $length);
}

sub mime_encode {
    my ($text, $enc) = @_;
    $enc ||= guess_encoding($text);
    $text = encode("MIME-Header", decode($enc, $text));
    $text =~ s/\r?\n/\r\n/g;
    return $text;
}

1;
